package com.ruoyi.yljf.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.ruoyi.common.constant.CacheConstants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.security.service.TokenService;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.vo.SysDictDataVO;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.yljf.domain.*;
import com.ruoyi.yljf.domain.bo.ResBO;
import com.ruoyi.yljf.domain.bo.ResBOV2;
import com.ruoyi.yljf.domain.dto.CourseDTO;
import com.ruoyi.yljf.domain.dto.WelfareAreaQueryDTO;
import com.ruoyi.yljf.domain.enums.yljfEnums;
import com.ruoyi.yljf.domain.vo.*;
import com.ruoyi.yljf.mapper.*;
import com.ruoyi.yljf.service.ICollectRecordService;
import com.ruoyi.yljf.service.ICoursePackageService;
import com.ruoyi.yljf.service.ILecturerService;
import com.ruoyi.yljf.util.CommonUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.yljf.service.ICourseService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.swing.tree.TreeNode;

/**
 * 课程Service业务层处理
 * 
 * @author TC
 * @date 2025-02-19
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {

	@Resource
	private ICoursePackageService coursePackageService;
	@Resource
	private LecturerMapper lecturerMapper;
	@Resource
    private CourseMapper courseMapper;
	@Resource
	private ISysDictDataService dictDataService;
	@Resource
	private CoursePackageMapper coursePackageMapper;
	@Resource
	private PharmacyMapper pharmacyMapper;
	@Resource
	private OrderMapper orderMapper;
	@Resource
	private CommonUtils commonUtils;
	@Resource
	private ICollectRecordService collectRecordService;
	@Resource
	private ILecturerService lecturerService;
	@Resource
	private SysUserMapper sysUserMapper;
	@Resource
	private RecordMapper recordMapper;
    /**
     * 查询课程列表
     * 
     * @param course 课程
     * @return 课程
     */
    @Override
    public List<Course> selectCourseList(Course course) {
    	LambdaQueryWrapper<Course> queryWrapper = Wrappers.lambdaQuery();
        if (StringUtils.isNotEmpty(course.getName())) {
			queryWrapper.like(Course::getName, course.getName());
		}
        if (StringUtils.isNotEmpty(course.getImg())) {
			queryWrapper.eq(Course::getImg, course.getImg());
		}
        if (StringUtils.isNotEmpty(course.getType())) {
			queryWrapper.eq(Course::getType, course.getType());
		}
        if (StringUtils.isNotEmpty(course.getSubject())) {
			queryWrapper.eq(Course::getSubject, course.getSubject());
		}
        if (StringUtils.isNotEmpty(course.getTimeCount())) {
			queryWrapper.eq(Course::getTimeCount, course.getTimeCount());
		}
        if (StringUtils.isNotEmpty(course.getChargeFree())) {
			queryWrapper.eq(Course::getChargeFree, course.getChargeFree());
		}
        if (StringUtils.isNotEmpty(course.getGrade())) {
			queryWrapper.eq(Course::getGrade, course.getGrade());
		}
        if (StringUtils.isNotNull(course.getPrice())) {
			queryWrapper.eq(Course::getPrice, course.getPrice());
		}
        if (StringUtils.isNotNull(course.getPlayCount())) {
			queryWrapper.eq(Course::getPlayCount, course.getPlayCount());
		}
        if (StringUtils.isNotEmpty(course.getInfo())) {
			queryWrapper.eq(Course::getInfo, course.getInfo());
		}
        if (StringUtils.isNotEmpty(course.getCreateType())) {
			queryWrapper.eq(Course::getCreateType, course.getCreateType());
		}
        if (StringUtils.isNotNull(course.getCreateId())) {
			queryWrapper.eq(Course::getCreateId, course.getCreateId());
		}
        if (StringUtils.isNotNull(course.getSubjectId())) {
			queryWrapper.eq(Course::getSubjectId, course.getSubjectId());
		}
        if (StringUtils.isNotNull(course.getLecturerId())) {
			queryWrapper.eq(Course::getLecturerId, course.getLecturerId());
		}

		List<Course> courses = courseMapper.selectList(queryWrapper);
		// 提取所有 lecturerId
		if (ObjectUtils.isNotEmpty(courses)) {
		Set<Long> lecturerIds = courses.stream()
				.map(Course::getLecturerId)
				.filter(Objects::nonNull)
				.collect(Collectors.toSet());
		// 批量查询讲师姓名
		Map<Long, String> lecturerNameMap = lecturerService.getNamesByIds(lecturerIds);
		// 合并数据
		courses.forEach(c -> c.setLecturerName(lecturerNameMap.get(c.getLecturerId())));
		}
		return courses;
    }

	@Override
	public List<HomeCourseVO> queryCourseList(CourseDTO courseDTO) {
		List<HomeCourseVO> collect = new ArrayList<>();
		List<Course> courses = courseMapper.selectList(
				new LambdaQueryWrapper<Course>()
						.like(StringUtils.isNotEmpty(courseDTO.getKeyWord()),Course::getName, courseDTO.getKeyWord())
						.eq((StringUtils.isNotNull(courseDTO.getGrade())),Course::getGrade, courseDTO.getGrade())
						.eq((StringUtils.isNotNull(courseDTO.getIsFeatured())),Course::getIsFeatured, courseDTO.getIsFeatured())
						.eq((StringUtils.isNotNull(courseDTO.getSecondaryType())),Course::getSecondaryType, courseDTO.getSecondaryType())
		);

		if (ObjectUtils.isNotNull(courses)) {
			collect = BeanUtil.copyToList(courses, HomeCourseVO.class);
		}
		return collect;
	}


	@Override
	public List<HomeCourseVO> QueryHomeCourseList(List<Course> list) {
		List<HomeCourseVO> collect = new ArrayList<>();

		if (ObjectUtils.isNotNull(list)) {
			collect = BeanUtil.copyToList(list, HomeCourseVO.class);
		}
		return collect;
	}

	@Override
	public List<Course> queryCourseList(WelfareAreaQueryDTO dto) {
		LambdaQueryWrapper<Course> eq = new LambdaQueryWrapper<Course>()
				.like(StringUtils.isNotEmpty(dto.getKeyWord()), Course::getName, dto.getKeyWord())
				.eq((StringUtils.isNotEmpty(dto.getGrade())), Course::getGrade, dto.getGrade())
				.eq((StringUtils.isNotEmpty(dto.getChargeFree())), Course::getChargeFree, dto.getChargeFree())
				.eq((StringUtils.isNotEmpty(dto.getType())), Course::getType, dto.getType())
				.eq((StringUtils.isNotNull(dto.getLecturerId())), Course::getLecturerId, dto.getLecturerId());

		if (StringUtils.isNotNull(dto.getOrder())) {
			if ("asc".equals(dto.getOrder())) {
				eq.orderByAsc(Course::getCreateTime);
			}else if ("desc".equals(dto.getOrder())) {
				eq.orderByDesc(Course::getCreateTime);
			}
		}
		List<Course> courses = courseMapper.selectList(eq);
		return courses;
	}

	@Override
	public CourseDetailVO queryById(Long id, HttpServletRequest request) {
		//查询课程数据
		Course course = this.courseMapper.selectById(id);
		CourseDetailVO courseDetailVO = new CourseDetailVO(course);
		courseDetailVO.setNoticeType(yljfEnums.NOTICE_TYPE_COURSE.getCode());
		courseDetailVO.setCreateTime(course.getCreateTime());

		// 为 courseDetailVO 设置最后播放时间和最后播放的章节id
		if(commonUtils.userIfLogin(request)) {
			Long userId = SecurityUtils.getUserId();
			LambdaQueryWrapper<Record> wrapper = new LambdaQueryWrapper<>();
			wrapper.select(Record::getOffTime, Record::getSectionId) // 通过方法引用代替字符串
					.eq(Record::getCourseId, id)
					.eq(Record::getUserId, userId)
					.orderByDesc(Record::getId)
					.last("limit 1");
			Record record = recordMapper.selectOne(wrapper);
			if (ObjectUtils.isNotEmpty(record)) {
				courseDetailVO.setPlaybackTime(String.valueOf(record.getOffTime()));
				courseDetailVO.setPlaybackPackageId(record.getSectionId());
				CoursePackage coursePackage = coursePackageMapper.selectById(record.getSectionId());
				if (ObjectUtils.isNotEmpty(coursePackage)) {
					courseDetailVO.setPlaybackUrl(coursePackage.getFilePath());
				}
			}
		}

		//需要提前判断用户是否登录
		boolean b = commonUtils.userIfLogin(request);
		if (b == true) {
			Long userId = SecurityUtils.getUserId();
			List<Order> orders = orderMapper.selectList(
					new LambdaQueryWrapper<>(Order.class)
							// 条件1：当前用户购买且未赠送的订单
							.eq(Order::getUserId, userId)
							.eq(Order::getOrderType,1)
							.eq(Order::getDishId,course.getId())
							.eq(Order::getIsSend, "N")
							.or()
							// 或条件2：送给当前用户的订单（无论赠送状态）
							.eq(Order::getSendUserId, userId));
			if (ObjectUtils.isNotEmpty(orders)) {
				courseDetailVO.setIfBuy(true);
			}
			boolean ifCollect = collectRecordService.ifCollect(yljfEnums.NOTICE_TYPE_COURSE.getCode(), id, userId);
			courseDetailVO.setIfCollect(ifCollect);
		}

		if (ObjectUtils.isNotNull(course)) {
			//查询章节数据
			LambdaQueryWrapper<CoursePackage> eq = new LambdaQueryWrapper<>(CoursePackage.class)
					.eq(CoursePackage::getCourseId, course.getId());
			Long l = coursePackageMapper.selectCount(eq);
			courseDetailVO.setSectionCount(l.toString());

			//封装章节列表数据
			List<PackageVO> packageVOS = coursePackageService.getByCourseID(id);
			courseDetailVO.setList(packageVOS);
			if ("pharmacy".equals(course.getCreateType())) {
				Pharmacy pharmacy = pharmacyMapper.selectById(course.getCreateId());
				courseDetailVO.setUserName(pharmacy.getPharmacyName());
				courseDetailVO.setUserImg(pharmacy.getPharmacyImg());
			} else if("user".equals(course.getCreateType())) {
				SysUser sysUser = sysUserMapper.selectUserById(course.getCreateId());
				courseDetailVO.setUserName(sysUser.getUserName());
				courseDetailVO.setUserImg(sysUser.getAvatar());
			}
		}
		return courseDetailVO;
	}

	@Override
	public List<CourseTypeVO> getSiftCourse(List<SysDictDataVO> secondaryType) {
        return secondaryType.stream().map(item -> {
			CourseTypeVO siftCourseVO = new CourseTypeVO(item);
			List<Course> courses = courseMapper.selectList(
					new LambdaQueryWrapper<Course>()
							.eq(Course::getIsFeatured, "Y")
							.eq(Course::getSecondaryType, item.getValue())
							.orderByDesc(Course::getId).last("limit 4")
			);
			siftCourseVO.setList(courses.stream().map(HomeCourseVO::new).collect(Collectors.toList()));
			return siftCourseVO;
		}).collect(Collectors.toList());
	}

	@Override
	public CourseTypeVO queryPrimaryCourse() {
		List<Course> courses = courseMapper.selectList(
				new LambdaQueryWrapper<Course>()
						.eq(Course::getGrade, "primary")
						.orderByDesc(Course::getId).last("limit 4")
		);
		List<HomeCourseVO> collect = courses.stream().map(HomeCourseVO::new).collect(Collectors.toList());
		return  new CourseTypeVO("入门必学","primary",collect);

	}

	@Override
	public CourseTypeVO queryStarCourse() {
		List<Long> ids = lecturerMapper.selectStarId();
		List<Course> courses = courseMapper.selectList(
				new LambdaQueryWrapper<Course>()
						.eq(Course::getType, yljfEnums.VIDEO.getCode())
						.in(Course::getLecturerId,ids)
						.orderByDesc(Course::getId).last("limit 4")
		);
		List<HomeCourseVO> collect = courses.stream().map(HomeCourseVO::new).collect(Collectors.toList());
		return  new CourseTypeVO("名家视频","star",collect);
	}

	@Override
	public List<HomeCourseVO> queryStarList() {
		List<HomeCourseVO> collect = new ArrayList<>();
		List<Long> ids = lecturerMapper.selectStarId();
		List<Course> courses = courseMapper.selectList(
				new LambdaQueryWrapper<Course>()
						.eq(Course::getType, yljfEnums.VIDEO.getCode())
						.in(Course::getLecturerId,ids)
		);
		if (ObjectUtils.isNotNull(courses)) {
			collect = BeanUtil.copyToList(courses, HomeCourseVO.class);
		}
		return collect;
	}

	@Override
	public List queryWelfareAreaType() {

		//课程类型
		List<SysDictDataVO> courseType = dictDataService.selectDictDataList("course_type");
		ArrayList<WelfareAreaTypeVO> welfareAreaTypeVOS = new ArrayList<>();
		WelfareAreaTypeVO vo1 = new WelfareAreaTypeVO();
		vo1.setLabel("分类");
		vo1.setValue("type");
		List<ResBO> bo1 = new ArrayList<>();
		courseType.forEach(item ->{
			ResBO resBO1 = new ResBO(item.getLabel(), item.getValue());
			bo1.add(resBO1);
		});
		vo1.setList(bo1);
		welfareAreaTypeVOS.add(vo1);

		//主讲列表
		List<Lecturer> Lecturers =lecturerMapper.selectList(new QueryWrapper<Lecturer>());
		WelfareAreaTypeVO vo2 = new WelfareAreaTypeVO();
		vo2.setLabel("主讲");
		vo2.setValue("lecturer_id");
		List<ResBO> bo2 = new ArrayList<>();
		Lecturers.forEach(item ->{
			ResBO resBO2 = new ResBO(item.getLecturerName(), item.getId().toString());
			bo2.add(resBO2);
		});
		vo2.setList(bo2);
		welfareAreaTypeVOS.add(vo2);

		//收费类型
		List<SysDictDataVO> sysYesNoList = dictDataService.selectDictDataList("sys_yes_no");
		WelfareAreaTypeVO vo3 = new WelfareAreaTypeVO();
		vo3.setLabel("类型");
		vo3.setValue("charge_free");
		List<ResBO> bo3 = new ArrayList<>();
		sysYesNoList.forEach(item ->{
			String chargeType = item.getValue().equals("Y") ? "免费" : "收费";
			ResBO resBO3 = new ResBO(chargeType, item.getValue());
			bo3.add(resBO3);
		});
		vo3.setList(bo3);
		welfareAreaTypeVOS.add(vo3);

		//分级
		List<SysDictDataVO> gradeTypeList = dictDataService.selectDictDataList("grade_type");
		WelfareAreaTypeVO vo4 = new WelfareAreaTypeVO();
		vo4.setLabel("级别");
		vo4.setValue("grade");
		List<ResBO> bo4 = new ArrayList<>();
		gradeTypeList.forEach(item ->{
			ResBO resBO4 = new ResBO(item.getLabel(), item.getValue());
			bo4.add(resBO4);
		});
		vo4.setList(bo4);
		welfareAreaTypeVOS.add(vo4);


		//排序
		WelfareAreaTypeVO vo5 = new WelfareAreaTypeVO();
		vo5.setLabel("排序");
		vo5.setValue("order");
		List<ResBO> bo5 = new ArrayList<>();
		ResBO resBO5 = new ResBO("正序", "asc");
		ResBO resBO6 = new ResBO("倒叙", "desc");
		bo5.add(resBO5);
		bo5.add(resBO6);
		vo5.setList(bo5);
		welfareAreaTypeVOS.add(vo5);

		return welfareAreaTypeVOS;
	}

	@Override
	public List queryWelfareAreaTypeV2() {

		//课程类型
		List<SysDictDataVO> courseType = dictDataService.selectDictDataList("course_type");
		ArrayList<WelfareAreaTypeVOV2> welfareAreaTypeVOS = new ArrayList<>();
		WelfareAreaTypeVOV2 vo1 = new WelfareAreaTypeVOV2();
		vo1.setLabel("分类");
		vo1.setValue("type");
		List<ResBOV2> bo1 = new ArrayList<>();
		courseType.forEach(item ->{
			ResBOV2 resBO1 = new ResBOV2(item.getLabel(), vo1.getValue(),item.getValue());
			bo1.add(resBO1);
		});
		vo1.setList(bo1);
		welfareAreaTypeVOS.add(vo1);

		//主讲列表
		List<Lecturer> Lecturers =lecturerMapper.selectList(new QueryWrapper<Lecturer>());
		WelfareAreaTypeVOV2 vo2 = new WelfareAreaTypeVOV2();
		vo2.setLabel("主讲");
		vo2.setValue("lecturerId");
		List<ResBOV2> bo2 = new ArrayList<>();
		Lecturers.forEach(item ->{
			ResBOV2 resBO2 = new ResBOV2(item.getLecturerName(), vo2.getValue(), item.getId().toString());
			bo2.add(resBO2);
		});
		vo2.setList(bo2);
		welfareAreaTypeVOS.add(vo2);

		//收费类型
		List<SysDictDataVO> sysYesNoList = dictDataService.selectDictDataList("sys_yes_no");
		WelfareAreaTypeVOV2 vo3 = new WelfareAreaTypeVOV2();
		vo3.setLabel("类型");
		vo3.setValue("chargeFree");
		List<ResBOV2> bo3 = new ArrayList<>();
		sysYesNoList.forEach(item ->{
			String chargeType = item.getValue().equals("Y") ? "免费" : "收费";
			ResBOV2 resBO3 = new ResBOV2(chargeType, vo3.getValue(),item.getValue());
			bo3.add(resBO3);
		});
		vo3.setList(bo3);
		welfareAreaTypeVOS.add(vo3);

		//分级
		List<SysDictDataVO> gradeTypeList = dictDataService.selectDictDataList("grade_type");
		WelfareAreaTypeVOV2 vo4 = new WelfareAreaTypeVOV2();
		vo4.setLabel("级别");
		vo4.setValue("grade");
		List<ResBOV2> bo4 = new ArrayList<>();
		gradeTypeList.forEach(item ->{
			ResBOV2 resBO4 = new ResBOV2(item.getLabel(), vo4.getValue(),item.getValue());
			bo4.add(resBO4);
		});
		vo4.setList(bo4);
		welfareAreaTypeVOS.add(vo4);

		//排序
		WelfareAreaTypeVOV2 vo5 = new WelfareAreaTypeVOV2();
		vo5.setLabel("排序");
		vo5.setValue("order");
		List<ResBOV2> bo5 = new ArrayList<>();
		ResBOV2 resBO5 = new ResBOV2("正序", vo5.getValue(),"asc");
		ResBOV2 resBO6 = new ResBOV2("倒叙", vo5.getValue(),"desc");
		bo5.add(resBO5);
		bo5.add(resBO6);
		vo5.setList(bo5);
		welfareAreaTypeVOS.add(vo5);

		return welfareAreaTypeVOS;
	}

	@Override
	public List<Course> queryCourseList1(CourseDTO courseDTO) {
		return courseMapper.selectList(
				new LambdaQueryWrapper<Course>()
						.like(StringUtils.isNotEmpty(courseDTO.getKeyWord()),Course::getName, courseDTO.getKeyWord())
						.eq((StringUtils.isNotNull(courseDTO.getGrade())),Course::getGrade, courseDTO.getGrade())
						.eq((StringUtils.isNotNull(courseDTO.getIsFeatured())),Course::getIsFeatured, courseDTO.getIsFeatured())
						.eq((StringUtils.isNotNull(courseDTO.getSecondaryType())),Course::getSecondaryType, courseDTO.getSecondaryType())
		);
	}


}
